#!/usr/bin/env perl

use utf8;
use strict;
use File::Basename;
use File::Spec::Functions;

sub getAbspath(){
    my $file    = $_[0];
    my $dir     = dirname($file);
    my $cwd     = $ENV{'PWD'}, my $real_path;

    chdir $dir;
    if( -d $file){
        $real_path = $ENV{'PWD'};
    }
    else{
        $real_path = catfile($ENV{'PWD'}, basename($file));
    }
    chdir $cwd;

    $real_path;
}

my ($f, $s, $t) = @ARGV;

my $s_name, my $d_name;


if(defined $t){
    $s_name = $s;
    $d_name = $t;
}
else{
    $s_name = $f;
    $d_name = $s;
}

if(!($s_name =~ /\A\//)){
    $s_name = &getAbspath($s_name);
}

if ( -d $d_name){
    $d_name = catfile(&getAbspath($d_name), basename($s_name));
}
else{
    $d_name = &getAbspath($d_name);
}

print "$d_name ===> $s_name\n";

if(defined $t){
    symlink $s_name, $d_name or die "Can't link $d_name to $s_name:$!.";
}
else{
    link $s_name, $d_name or die "Can't link $d_name to $s_name:$!.";
}
